#!/usr/bin/env python
import email
import md5
from sessions import Session

from time import gmtime, strftime

from google.appengine.ext.webapp import RequestHandler
from google.appengine.api import users
from google.appengine.ext import db

from templates import run, render, redirect, out
from models import UserActions,EmailActionUpdate

class EmailSettings(RequestHandler):
   
	session = Session()

	def get(self):
		user = users.get_current_user()
		emailSettings = EmailActionUpdate.gql("WHERE email = :1", user.email()).get()

		if emailSettings:
			emailAddy = "%s@noisewater.net" % emailSettings.passwd
		else:
			emailAddy = None

		if self.session['emailError']:
			error = self.session['emailError']
			del(self.session['emailError'])
		else:
			error = None

		render(self, 'emailsettings.html', values={ 'loglink':users.create_logout_url("/"), 
													'loglabel': 'logout', 
													'nick':user.nickname(), 
													'emailAddy':emailAddy,
													'error': error})

	def post(self):
		if not self.request.get('emailpass'):
			self.session['emailError'] = 'Please enter a password, it\'s required'
			redirect(self, '/emailsettings')
			
		else:
			user = users.get_current_user()
			passSetup = "%s%s%s" % (self.request.get('emailpass'), strftime("%S", gmtime()), user.email())
			emailpass = md5.new(passSetup).hexdigest()[:8]
			emailSettings = EmailActionUpdate.gql("WHERE email = :1", user.email()).get()

			if emailSettings:
				emailSettings.passwd = emailpass
				emailSettings.put()
			else:
				emailSettings = EmailActionUpdate()
				emailSettings.email = user.email()
				emailSettings.nickname = user.nickname()
				emailSettings.passwd = emailpass
				emailSettings.put()

			redirect(self, "/emailsettings")

        
        

class EmailUpdate(RequestHandler):
    def post(self):
        sender = self.request.GET.get("from", "")
        recipient = self.request.GET.get("to","")
        message = email.message_from_string(self.request.body)
        
        passwd = message.get("To", None).split('@')[0]
        emailInfo = EmailActionUpdate.gql("WHERE passwd = :1", passwd).get()
        
        emailaddy = emailInfo.email
        unickname = emailInfo.nickname

        if not message.is_multipart():
            ripple = message.get_payload()
        else:
            for part in msg.walk():
                if part.get_content_type() == "text/plain":
                    ripple = part.get_payload()
                    break
                else:
                    ripple = None

        if ripple:
            user = users.User(emailaddy)
            ua = UserActions(actions=ripple, email=user, nickname=unickname)
            ua.put()
        
        return

def main():
	run([('/emailsettings', EmailSettings),
		 ('/emailupdate',EmailUpdate)])

if __name__ == '__main__': main()
